"""Elasticsearch客户端配置"""
from elasticsearch import Elasticsearch
import logging

logger = logging.getLogger(__name__)

# 创建ES客户端
es_client = Elasticsearch(
    ['http://localhost:9200'],
    # 如果启用了安全认证
    # basic_auth=('elastic', 'your_password'),
    request_timeout=30
)


def check_es_connection():
    """检查ES连接"""
    try:
        if es_client.ping():
            logger.info("✅ Elasticsearch连接成功")
            return True
        else:
            logger.error("❌ Elasticsearch连接失败")
            return False
    except Exception as e:
        logger.error(f"❌ Elasticsearch连接错误: {e}")
        return False


def create_content_index():
    """创建内容索引"""
    index_name = "xiaohongshu_contents"
    
    # 索引映射
    index_mapping = {
        "mappings": {
            "properties": {
                "id": {"type": "integer"},
                "user_id": {"type": "integer"},
                "title": {
                    "type": "text",
                    "analyzer": "ik_max_word",  # 中文分词
                    "search_analyzer": "ik_max_word"
                },
                "content": {
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "search_analyzer": "ik_max_word"
                },
                "tags": {
                    "type": "keyword"
                },
                "like_count": {"type": "integer"},
                "view_count": {"type": "integer"},
                "comment_count": {"type": "integer"},
                "collect_count": {"type": "integer"},
                "media_type": {"type": "integer"},
                "media_urls": {"type": "keyword"},
                "status": {"type": "integer"},
                "created_at": {"type": "date"},
                "author_nickname": {"type": "keyword"}
            }
        },
        "settings": {
            "number_of_shards": 1,
            "number_of_replicas": 0
        }
    }
    
    try:
        # 检查索引是否存在
        if not es_client.indices.exists(index=index_name):
            # 创建索引（ES 8.x 兼容：直接传入参数而不是使用 body）
            es_client.indices.create(index=index_name, **index_mapping)
            logger.info(f"✅ 创建索引成功: {index_name}")
        else:
            logger.info(f"索引已存在: {index_name}")
        
        return True
    except Exception as e:
        logger.error(f"❌ 创建索引失败: {e}")
        return False


def index_content(document):
    """索引内容到ES"""
    try:
        es_client.index(
            index="xiaohongshu_contents",
            id=document['id'],
            document=document
        )
        return True
    except Exception as e:
        logger.error(f"索引内容失败: {e}")
        return False


def search_content(keyword, limit=20):
    """搜索内容"""
    try:
        query = {
            "bool": {
                "should": [
                    {
                        "match": {
                            "title": {
                                "query": keyword,
                                "boost": 3.0  # 标题权重更高
                            }
                        }
                    },
                    {
                        "match": {
                            "content": {
                                "query": keyword,
                                "boost": 1.0
                            }
                        }
                    },
                    {
                        "term": {
                            "tags": keyword
                        }
                    }
                ],
                "minimum_should_match": 1
            }
        }
        
        # ES 8.x 兼容：使用 query 参数而不是 body
        response = es_client.search(
            index="xiaohongshu_contents",
            query=query,
            sort=[
                {"_score": {"order": "desc"}},
                {"like_count": {"order": "desc"}},
                {"created_at": {"order": "desc"}}
            ],
            size=limit
        )
        
        # 提取结果
        results = []
        for hit in response['hits']['hits']:
            results.append(hit['_source'])
        
        return results
        
    except Exception as e:
        logger.error(f"搜索失败: {e}")
        return []


def sync_all_contents_to_es(db):
    """将所有内容同步到ES"""
    from models.models import Content
    import json
    
    try:
        contents = db.query(Content).filter(Content.status == 1).all()
        
        count = 0
        for content in contents:
            # 解析标签
            tags = []
            if content.tags:
                if isinstance(content.tags, str):
                    try:
                        tags = json.loads(content.tags)
                    except:
                        tags = []
                else:
                    tags = content.tags or []
            
            # 构建ES文档
            doc = {
                'id': content.id,
                'user_id': content.user_id,
                'title': content.title or '',
                'content': content.content or '',
                'tags': tags,
                'like_count': content.like_count or 0,
                'view_count': content.view_count or 0,
                'comment_count': content.comment_count or 0,
                'collect_count': content.collect_count or 0,
                'media_type': content.media_type or 1,
                'media_urls': content.media_urls or '',
                'status': content.status,
                'created_at': content.created_at.isoformat() if content.created_at else None
            }
            
            # 索引到ES
            index_content(doc)
            count += 1
        
        logger.info(f"✅ 同步成功: {count} 条内容")
        return True
        
    except Exception as e:
        logger.error(f"同步失败: {e}")
        return False

